// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package session

import (
	"context"
	"time"
)

// Service is a session storage service.
//
// It provides a set of methods for managing sessions and events.
type Service interface {
	Create(context.Context, *CreateRequest) (*CreateResponse, error)
	Get(context.Context, *GetRequest) (*GetResponse, error)
	List(context.Context, *ListRequest) (*ListResponse, error)
	Delete(context.Context, *DeleteRequest) error
	// AppendEvent is used to append an event to a session, and remove temporary state keys from the event.
	AppendEvent(context.Context, Session, *Event) error
}

// InMemoryService returns an in-memory implementation of the session service.
func InMemoryService() Service {
	return &inMemoryService{
		appState:  make(map[string]stateMap),
		userState: make(map[string]map[string]stateMap),
	}
}

// CreateRequest represents a request to create a session.
type CreateRequest struct {
	AppName string
	UserID  string
	// SessionID is the client-provided ID of the session to create.
	// Optional: if not set, it will be autogenerated.
	SessionID string
	// State is the initial state of the session.
	State map[string]any
}

// CreateResponse represents a response for newly created session.
type CreateResponse struct {
	Session Session
}

// GetRequest represents a request to get a session.
type GetRequest struct {
	AppName   string
	UserID    string
	SessionID string

	// NumRecentEvents returns at most NumRecentEvents most recent events.
	// Optional: if zero, the filter is not applied.
	NumRecentEvents int
	// After returns events with timestamp >= the given time.
	// Optional: if zero, the filter is not applied.
	After time.Time
}

// GetResponse represents a response from [Service.Get].
type GetResponse struct {
	Session Session
}

// ListRequest represents a request to list sessions.
type ListRequest struct {
	AppName string
	UserID  string
}

// ListResponse represents a response from [Service.List].
type ListResponse struct {
	Sessions []Session
}

// DeleteRequest represents a request to delete a session.
type DeleteRequest struct {
	AppName   string
	UserID    string
	SessionID string
}
